let parents = '', arr = [], element = '', currentIndex = '';
var uploadImg = [] , uploadfile = [] , fileName = [] , gather = [];

function  GetQueryString(name)
{
	var  reg = new  RegExp( "(^|&)" + name + "=([^&]*)(&|$)" );
	var  r = window.location.search.substr(1).match(reg);
	if (r!= null ) return   unescape(r[2]); return  null ;
}

$().ready(async function() {
	validateRule();
	await selectDomCreate()
	await selCertificateList()
	let names = $('#name').val().replace(/&amp;/g, "&")
	$('#name').val(names)

	let zyNames = $("#zyNames").val();
	let spUrls = $("#spUrls").val();
	let zySorts = $("#zySorts").val();

	zyNames = zyNames?.split(',')
	spUrls =  spUrls?.split(',')
	zySorts = zySorts?.split(',')

	//课程资源选择器


	let str = '';
	spUrls?.map(function (v,k){
		str += `
			<div class="link">
				<input placeholder="请输入资源名称" class="form-control title" type="text" value="${zyNames[k]}">
				<input placeholder="请输入视频链接" class="form-control video" type="text" value="${v}">
				<p class="priority"><input type="text" class="form-control number" value="${zySorts[k]}"></p>
				<span class="iconclose remove"><img src="../../../img/close.png"></span>
			</div>
		`
	})

	$(".resource").append(str)

	str = '';
	if( $("#wdUrls").val() ){
		uploadfile = $("#wdUrls").val().split(',')
		uploadfile?.map(function (v,k){
			str += `
		<div class="closeBtn">
			<img class="upImg" src="../../../img/document.png" width="30"/> ${v}
			<span class="iconclose close1" data-index="${k}" ><img src="../../../img/close.png"></span>
		</div>
	  `;
		})
		$(".listAll").html(str)
	}

	str = '';
	if( $("#tpUrls").val() ) {
		uploadImg = $("#tpUrls").val().split(',')
		uploadImg?.map(function (v, k) {
			str += `
				<div class="closeBtn">
					<img class="upImg" src="${v}" />
					<span class="iconclose close2" data-index="${k}" ><img src="../../../img/close.png"></span>
				</div>
			  `;
		})
		$(".listImg").html(str)
	}

});

$.validator.setDefaults({
	submitHandler : function() {
		update();
	}
});


function update() {
	let video = [] , zySorts = [] , tle = [];

	if( !$("#name").val() ){
		layer.msg('请输入章节名称')
		return false
	}

	let len = document.getElementsByClassName('link');

	for( let is = 0; is <= len.length - 1; is++ ){

		if( len[is].querySelector('.title').value ){
			tle.push( len[is].querySelector('.title').value )
		}
		// else{
		// 	layer.msg('请输入资源名称')
		// 	return false
		// }
		if( len[is].querySelector('.video').value ){
			video.push( len[is].querySelector('.video').value )
		}
		// else{
		// 	layer.msg('请输入视频链接')
		// 	return false
		// }
		if( len[is].querySelector('.number').value ){
			zySorts.push( len[is].querySelector('.number').value )
		}
		// else{
		// 	layer.msg('请输入优先级')
		// 	return false
		// }

	}

	$("#zyNames").val(tle.join(','))
	$("#spUrls").val(video.join(','))
	$("#zySorts").val(zySorts.join(','))

	let provinceDom = $('#province').val()
	let parenIdNamesDom = $('#parenIdNames').val()
	let parenIdNameDom = $('#parenIdName').val()
	if(provinceDom !== '' && parenIdNamesDom !=="") {
		$('#parenId').hide()
		$('#managementResourcesId').hide()
	}
	var formData = $('#signupForm').serializeArray();
	var jsonData = {};
	$.each(formData, function(index, field){
		if(field.name === 'parenIds') {
			if(field.value !== '') {
				jsonData['parenId'] = field.value
			}
		}

		jsonData[field.name] = field.value;
	});
	if(provinceDom === '') {
		jsonData['parenId'] = $('#parenId').val()
		jsonData['managementResourcesId'] = $('#managementResourcesId').val()
	}else {
		if(parenIdNamesDom === '' && parenIdNameDom === '') {
			jsonData['parenId'] = $('#province').val()
		}
		if(parenIdNamesDom !== '') {
			if(parenIdNameDom === '') {
				jsonData['level'] = 2
			}else {
				jsonData['level'] = 3
			}
		}
	}
	delete jsonData.parenIds
	delete jsonData?.managementResourcesId_text
	delete jsonData?.parenId_text
	let formDates = new FormData();

	for (const jsonDataKey in jsonData) {
		formDates.append(jsonDataKey, jsonData[jsonDataKey]);
	}


	$.ajax({
		cache : true,
		type : "POST",
		url : "/jzweb/zykResourcesChapters/update",
		data :formDates,// 你的formid
		async : false,
		processData: false,
		contentType: false,
		error : function(request) {
			parent.layer.alert("Connection error");
		},
		success : function(data) {
			if (data.code == 0) {
				parent.layer.msg("操作成功");
				parent.reLoad();
				var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
				parent.layer.close(index);

			} else {
				parent.layer.alert(data.msg)
			}

		}
	});

}

$(".addElement").click(function (){
	let str = `<div class="link">
					<input name="" placeholder="请输入资源名称" class="form-control title" type="text">
	
					<input placeholder="请输入视频链接" class="form-control video" type="text">
					<p class="priority"><input type="text" class="form-control number"></p>
					<span class="iconclose remove"><img src="../../../img/close.png"></span>
				</div>`;

	$(".resource").append(str)

})

layui.use(['upload', 'layer'], function() {
	var $ = layui.jquery
		, upload = layui.upload
		, layer = layui.layer;
	upload.render({
		elem: '#test2'
		,url: '/common/sysFile/upload' //此处配置你自己的上传接口即可
		,accept: 'file' //普通文件
		,before: function(obj){
			layer.load(1)
			obj.preview(function (index, file, result) {
				fileName.push(file.name);
			})
		}
		,done: function(res){

			if( res.code == 0 ){
				layer.closeAll();
				let str = '' , srr = '' , url = '';
				gather = [];
				uploadfile.push(res.data);
				uploadfile.map(function (v,k){
					gather.push({name:fileName[k],file:v})
				})

				gather.map(function (v,k){
					str += `
						<div class="closeBtn">
							<img class="upImg" src="../../../img/document.png" width="30"/> ${v.file}
							<span class="iconclose close1" data-index="${k}" ><img src="../../../img/close.png"></span>
						</div>
					  `;
				})
				$(".listAll").html(str)
				$("#wdUrls").val(uploadfile.join(','))

			}

		}
		,error:function (res){
			layer.closeAll();
			layer.msg(res.msg)
		}
	});

	//图片上传
	var uploadInst = upload.render({
		elem: '#test1'
		,url: '/common/sysFile/upload' // 实际使用时改成您自己的上传接口即可。
		,multiple: true
		,before: function(obj){
			layer.load();
		}
		,done: function(res){
			if( res.code == 0 ){
				layer.closeAll();
				let str = '' ;
				uploadImg.push(res.data);
				$("#tpUrls").val( uploadImg.join(',') )
				uploadImg.map(function (v,k){
					str += `
						<div class="closeBtn">
							<img class="upImg" src="${v}" />
							<span class="iconclose close2" data-index="${k}" ><img src="../../../img/close.png"></span>
						</div>
					  `;
				})
				$(".listImg").html(str)
			}
		}
		,error:function (res){
			layer.closeAll();
			layer.msg(res.msg)
		}
	});

})


function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			name : {
				required : true
			}
		},
		messages : {
			name : {
				required : icon + "请输入名字"
			}
		}
	})
}

function removeContent(that, parent, arr, element, index , type) {
	let str = '';
	$(that).parent(parent).remove();
	arr.splice(index, 1);
	if( type == 1 ){
		let strUrl = [];
		arr.map(function (v,k){
			str += `
				<div class="closeBtn">
					<img class="upImg" src="../../../img/document.png" width="30"/> ${v}
					<span class="iconclose close1" data-index="${k}" ><img src="../../../img/close.png"></span>
				</div>
			  `;
			// strName.push(v.name)
			strUrl.push(v.url)
		})

		uploadImg = arr
		$("#wdUrls").val(strUrl.join(','))

	}else {
		arr.forEach(function (v, k) {
			str += `
			  <div class="closeBtn">
				<img class="upImg" src="${v}" />
				<span class="iconclose close2" data-index="${k}"><img src="../../../img/close.png"></span>
			  </div>
			`;
		});
		uploadImg = arr
		$("#tpUrls").val( uploadImg.join(',') )
	}

	$(element).html(str);
}

$(document).on('click', '.close2', function() {
	var currentIndex = $(this).data('index');
	arr =  uploadImg;
	parents = '.closeBtn';
	element = '.listImg';
	removeContent(this, parent, arr, element, currentIndex , 2);
});

$(document).on('click', '.close1', function() {
	var currentIndex = $(this).data('index');
	arr =  uploadfile;
	parents = '.closeBtn';
	element = '.listAll';
	removeContent(this, parent, arr, element, currentIndex , 1);
});

$(document).on('click', '.remove', function() {
	let num = $(".link").length - 1;
	if( num <= 0 ){
		layer.msg('已经是最后一个了')
		return false;
	}
	$(this).parents('.link').remove();
});


let flag
let flag1 = false
//选择器渲染
function selectDomCreate() {
	$('#province').on('change',async function (data) {
		let provinceId = $('#province').val();
		if(flag) {
			$('#parenIdNames').selectPageClear();
			const data = await zykManaParenIdNames(provinceId,1)
			$('#parenIdNames').selectPageData(data);
			return
		}
		 selCertificateTwoList(`/jzweb/zykResourcesChapters/list?parenId=${provinceId}&level=1`,'parenIdNames')
		flag = true
	})

	// 二级选项选择事件
	$('#parenIdNames').on('change',async function(data) {
		let provinceId = $('#parenIdNames').val();
		if(flag1) {
			$('#parenIdName').selectPageClear();
			const data = await zykManaParenIdNames(provinceId, 2)
			$('#parenIdName').selectPageData(data);
			return
		}
			selCertificateTwoList( `/jzweb/zykResourcesChapters/list?parenId=${provinceId}&level=2`,'parenIdName')
			flag1 = true
	});
	// });
}

//一级选择器
function selCertificateList() {
	$('#province').selectPage({
		showField: 'name',
		keyField: 'id',
		searchField: 'name',
		data: `/jzweb/zykManagementResources/list`,
		//向服务端提交的参数中，增加已选中的
		//设置返回-1，意为通知服务端返回空列表，初始化时使用
		params: function () {
			var pv = $('#province').val();
			return pv;
		},
		eAjaxSuccess: function (d) {
			var result;
			if (d) result = d.data;
			else result = undefined;
			return result;
			add.js
		},
	});

}

//二三级选择器
function selCertificateTwoList(url,dom) {
	 $(`#${dom}`).selectPage({
		showField: 'name',
		keyField: 'id',
		searchField: 'name',
		data: url,
		//向服务端提交的参数中，增加已选中的
		//设置返回-1，意为通知服务端返回空列表，初始化时使用
		eAjaxSuccess: function (d) {
			var result;
			if (d) result = d.data;
			else result = undefined;
			return result;
			add.js
		},
	});
}


//章节接口
function zykManaParenIdNames(id,level) {

	return  new Promise(function (resolve, reject) {
		$.ajax({
			type : "get",
			url : `/jzweb/zykResourcesChapters/list`,
			async : false,
			data:{parenId:id,level: level},
			error : function(request) {
				parent.layer.alert("Connection error");
			},
			success : function(data) {
				if (data.code == 0) {
					resolve(data.data.records)
				}

			}
		});
	})

}